/*eslint-disable*/
import React, {PureComponent} from "react";
import {
  Card,
  /* Table, Tabs, */
  // Icon,
  Button,
  Spin,
  Modal,
  Dropdown,
  Menu,
  Form,
  Radio,
  Input, Popconfirm,
} from "antd";
import {connect} from "dva";
import {withRouter} from "dva/router";
import {
  openNotificationWithIcon,
  isPhone,
  getPhoneUrlForHandle,
  getUuid,
} from "utils/comm";
import {getFormTitleKeyList} from "utils/formilyAppHelperUtil";
import moment from "moment";
import router from "umi/router";
import IframeWrapper, { IframeAutoFit } from "components/IframeWrapper";
import ProcessInfo from "./TemplateProcessInfo";
// import ExpandedRowContent from './ExpandedRowContent';
// import DealForm from '../processDealForm';
import FlowChartDetail from "../flowchartdetail";
// import { detailFormat } from '../../pages/flowmanage/formbuilder/nomalFn';
import CustomForm from "../customForm/CustomForm";
import RollbackForm from "../rollbackForm";
import ReturnBackForm from "./ReturnBackForm";
import SignForm from "./SignForm";
import AddSignForm from "./AddSignForm";
import TransferForm from "./TransferForm";
import DelayForm from "./DelayForm";
import RejectForm from "./RejectForm";
// import { formComment, formApproval } from './nomalData';
import RecordForm from "./RecordForm";
import ProcessRecord from "./TemplateProcessRecord";
import ApprovalForm from "./ApprovalForm";
import MoreBtnForm from "./MoreBtnForm";
import NextNodeForm from "./NextNodeForm";
import ReadHandleForm from "./ReadHandleForm";
import FileView from "components/FileView";
import styles from "./TemplateIndex.less";

// const { TabPane } = Tabs;
const {TextArea} = Input;
const isTrue = true;

@withRouter
@connect(({FlowHandle, loading, notice_msg: noticeModel}) => ({
  flowHandleStore: FlowHandle,
  loading,
  noticeThemeTypeList: noticeModel.noticeThemeTypeList,
}))
@Form.create()
// eslint-disable-next-line
class FlowDataDetail extends PureComponent {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
    this.isLogLoaded = false; // 用于tab切换请求控制
    this.taskId = "";

    this.basePagination = {
      size: "small",
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ["5", "10", "15", "20"],
      total: 0,
    };

    this.state = {
      // visible: false,
      formVisible: false,
      formDraftData: undefined,
      // 第一个非开始及结束类型的流程节点，状态为TODO,通知业务系统填充数据
      // noticeBusinessSystem: false,
      rollbackVisible: false,
      returnBackVisible: false,
      signVisible: false,
      addSignVisible: false,
      transferVisible: false,
      delayVisible: false,
      pictureVisible: false,
      rejectVisible: false,
      rollbackInfo: {},
      // expandedRowKeys: [],
      // taskformFields: [],
      // releaseNotice: "",
      // formValues: {},
      approvalVisible: false,
      moreBtnVisible: false,
      nextNodeVisible: false,
      forcePickIndex: 0,
      visibleTitle: "",
      comment: "",
      backVisible: false,
      readHandleVisible: false,
      attachInfoList: [],
      forcePickComplete:null,
      hasForcePick: false,
      titleText: '',
    };
  }

  /*
  columnsr = [
    { title: '任务名称', dataIndex: 'taskName', key: 'taskName' },
    {
      title: '任务类型',
      dataIndex: 'taskType',
      key: 'taskType',
      render: (text, record) => {
        if (record.taskType === 'multiUserTask') { // 用户类型（普通用户任务：userTask，会签任务：multiUserTask）
          return <span>会签任务</span>;
        } else if (record.taskType === 'userTask') {
          return <span>用户任务</span>;
        } else {
          return <span>text</span>
        }
      },
    },
    { title: '到达时间', dataIndex: 'createTime', key: 'createTime' },
    { title: '处理人', dataIndex: 'assignee', key: 'assignee' },
    {
      title: '操作',
      width: '100px',
      render: (text, record) => {
        if (record.taskType === 'multiUserTask') { // 用户类型（普通用户任务：userTask，会签任务：multiUserTask）
          return (
            <a className={styles.hq_ele} onClick={(e) => { e.preventDefault(); this.handleExpandable(record); }}>
              会签信息
              {// <Zcon type={this.status?'pack-up':'pack-down'} /> //}
              <Icon className={styles.icon_anticon} type={this.expandeId === record.taskId ? 'up' : 'down'} />
            </a>
          );
        } else {
          return <span>一</span>
        }
      },
    },
  ];

  columns = [
    { title: '处理时间', dataIndex: 'endTime', key: 'endTime' },
    { title: '处理环节', dataIndex: 'taskName', key: 'taskName' },
    { title: '处理人', dataIndex: 'assignee', key: 'assignee' },
    {
      title: '动作',
      dataIndex: 'type',
      key: 'type',
      render: (text) => {
        return <span>{text === 'rollback' ? '退回' : '正常处理'}</span>
      },
    },
    {
      title: '操作',
      dataIndex: 'opration',
      render: (text, record) => {
        return (
          <a onClick={(e) => { e.preventDefault(); this.handleDealFormVisible(true, record); }}>处理详情</a>
        );
      },
    }];
  */

  componentDidMount() {
    const {
      location,
      dispatch,
    } = this.props;
    const {taskId = "", processInstanceId = "", actype = ""} = location?.query ?? {};
    this.actype = actype;
    if (!processInstanceId) return;
    this.processInstanceId = processInstanceId;
    this.taskId = taskId;
    this.getDetailData();
    this.getNoticeThemeList();
    this.uuid = getUuid();

    // dispatch({
    //   type: "FlowHandle/getNextTaskDetail",
    //   payload: taskId,
    // });

    const userCode = sessionStorage.getItem("USER_CODE") ?? '';
    dispatch({
      type: "FlowHandle/updateReadFlag",
      payload: {taskId, userCode},
    });

  }

  componentDidUpdate(preProps) {
    const {
      location: {
        query: {processInstanceId = ""},
      },
    } = this.props;
    const {
      location: {
        query: {processInstanceId: preProcessInstanceId},
      },
    } = preProps;
    if (processInstanceId !== preProcessInstanceId) {
      this.getDetailData();
    }
  }

  componentWillUnmount() {
    const {dispatch} = this.props;
    dispatch({type: "FlowHandle/clearData"});
  }

  getDetailData = () => {
    const {dispatch, location} = this.props;
    const userCode = sessionStorage.getItem("USER_CODE") ?? '';
    dispatch({
      type: "FlowHandle/getProcess",
      payload: {processInstanceId: this.processInstanceId},
    });
    dispatch({
      type: "FlowHandle/getAttachInfoList",
      payload: {processInstanceId: this.processInstanceId, serviceType: 0},
    }).then(({ errCode, datas }) => {
      if (errCode === 0) {
        this.setState({attachInfoList: datas})
      }
    });
    const {taskId = ""} = location.query;
    if (taskId) {
      this.taskId = taskId;
      dispatch({
        type: "FlowHandle/queryCandidateTask",
        payload: {taskId:taskId , userCode},
      });

      // dispatch({
      //   type: "FlowHandle/getNextTaskDetail",
      //   payload: taskId,
      // });

      dispatch({
        type: "FlowHandle/getMustExpress",
        payload: {taskId},
      })
    }

    this.getFlowRecords();
    this.uuid = getUuid();
    // this.getCurrentTasks();
  };

  handleForcePick = () => {
    const {flowHandleStore} = this.props;

    const { candidateTask = {} } = flowHandleStore;

      const {nextNodeHandler = false} = candidateTask?.nodeAuth ?? {};
      if (nextNodeHandler) {
        this.getNextNodeHandler(this.taskId);
      } else {
        this.handleApprovalVisible(true, "handle", this.taskId);
      }

  }

  getNextNodeHandler = (taskId) => {
    const {dispatch} = this.props;
    dispatch({
      type: "FlowHandle/getNextTaskDetail",
      payload: taskId,
    }).then(({errCode, datas}) => {
      if (errCode !== 0) {
        return;
      }

      let hasForcePickNoPick = false;
      let hasForcePick = false;
      let tmpIndex = 0;
      datas.some((item, index) => {
        const {isPick = '0', forcePick = '0', dataTypeList=[]} = item;
        if (forcePick === '1' && dataTypeList.length > 0) {
          hasForcePick = true;
          if (isPick === '0') {
            hasForcePickNoPick = true;
            tmpIndex = index;
            return true;
          }
        }
      })
      this.setState({hasForcePick});
      if (hasForcePickNoPick) {
        this.setState({
          nextNodeVisible: true,
          forcePickIndex: tmpIndex,
          });
      } else {
        this.handleApprovalVisible(true, "handle", this.taskId);
      }
    });
  }

  getNoticeThemeList = () => {
    const {dispatch} = this.props;
    dispatch({type: "notice_msg/getNoticeThemeType"});
  };

  // 获取流程流转记录
  getFlowRecords = () => {
    const {dispatch} = this.props;
    const u = sessionStorage.getItem("USER_CODE");
    const {processInstanceId} = this;
    if (!processInstanceId) return;
    let taskResult = {};
    dispatch({
      type: "FlowHandle/getFlowRecords",
      payload: {processInstanceId},
    }).then(({errCode: _errCode, datas: _datas}) => {
      if (_errCode === 0) {
        // eslint-disable-next-line array-callback-return
        _datas.map(item => {
          if (item.children?.length > 0) {
            // eslint-disable-next-line array-callback-return
            item.children.map(v => {
              if (
                v.operatorCode === u &&
                v.status === "NORMAL" &&
                v?.taskStatus === "TODO"
              )
                taskResult = v;
            });
          } else if (
            item.operatorCode === u &&
            item.status === "NORMAL" &&
            item?.taskStatus === "TODO"
          ) {
            taskResult = item;
          } else if (
            item.nodeAuthShow === true &&
            item.nodeAuth.signIn === true
          ) {
            taskResult = item;
          }
        });
        dispatch({
          // 流程表单取流程实例ID去查询
          type: "FlowHandle/isExternalForm",
          payload: {instanceId: this.processInstanceId},
        }).then(({errCode, datas}) => {
          if (errCode === 0 && datas === true) {
            dispatch({
              type: "FlowHandle/filledExternalFormInfo",
              payload: {
                processInstanceId: this.processInstanceId,
                taskId: this.taskId
              },
            });
          } else {
            dispatch({
              type: "FlowHandle/getStartFormDetail",
              payload: {processInstanceId: this.processInstanceId},
            });
          }
        });
        // if (taskResult.taskId) {
        //   dispatch({ // 节点表单展示
        //     type: "FlowHandle/isExternalForm",
        //     payload: { taskId: taskResult.taskId },
        //   }).then(({ errCode, datas }) => {
        //     if (errCode === 0 && datas === true) {
        //       dispatch({
        //         type: "FlowHandle/filledExternalFormInfo",
        //         payload: { taskId: taskResult.taskId },
        //       })
        //     } else { // 全局表单展示
        //       dispatch({
        //         type: "FlowHandle/isExternalForm",
        //         payload: { instanceId: this.processInstanceId },
        //       }).then(({ errCode: errCode2, datas: datas2 }) => {
        //         if (errCode2 === 0 && datas2 === true) {
        //           dispatch({
        //             type: "FlowHandle/filledExternalFormInfo",
        //             payload: { processInstanceId: this.processInstanceId },
        //           })
        //         } else {
        //           dispatch({
        //             type: "FlowHandle/getStartFormDetail",
        //             payload: { processInstanceId: this.processInstanceId },
        //           });
        //         }
        //       })
        //     }
        //   })
        // }
        // else { // 全局表单展示
        //   dispatch({
        //     type: "FlowHandle/isExternalForm",
        //     payload: { instanceId: this.processInstanceId },
        //   }).then(({ errCode, datas }) => {
        //     if (errCode === 0 && datas === true) {
        //       dispatch({
        //         type: "FlowHandle/filledExternalFormInfo",
        //         payload: { processInstanceId: this.processInstanceId },
        //       })
        //     } else {
        //       dispatch({
        //         type: "FlowHandle/getStartFormDetail",
        //         payload: { processInstanceId: this.processInstanceId },
        //       });
        //     }
        //   })
        // }
      }
    });
  };

  /* // 获取当前任务列表
  getCurrentTasks = () => {
    const { dispatch } = this.props;
    if (!this.processInstanceId) return;
    const { tasksPage: { pageSize, current } } = this.state;
    dispatch({ type: 'FlowHandle/getCurrentTasks', payload: { processInstanceId: this.processInstanceId, pageSize, pageNum: current } });
  }

  // 获取处理日志
  getProcessLogs = () => {
    const { dispatch } = this.props;
    if (!this.processInstanceId) return;
    const { logsPage: { pageSize, current } } = this.state;
    dispatch({ type: 'FlowHandle/handleLogs', payload: { processInstanceId: this.processInstanceId, pageSize, pageNum: current } });
  }

  handleDealFormVisible = (visible, record = '') => {
    const { handleDetail = {} } = record || {};
    const { formInfo, rollbackInfo, releaseNotice, approval, comment } = handleDetail || {};
    this.title = '处理任务';
    this.record = record;
    if (formInfo) {
      const { fields = [], name } = formInfo || {};
      const newFileds = detailFormat(fields || []);
      const formValues = {};
      fields.forEach(ele => {
        const { code, value } = ele;
        if (code) formValues[code] = value;
      });
      this.title = name;
      this.setState({ taskformFields: newFileds, formValues, releaseNotice });
      this.customFormVisible(true);
      // return;
    } else if (rollbackInfo) {
      this.title = '退回';
      this.setState({ rollbackInfo, rollbackVisible: true });
      // return;
    } else {
      const defaultFields = [
        { ...formComment, value: comment },
        { ...formApproval, value: approval },
      ];
      const { noticeDescription, receivers } = releaseNotice || {};
      this.title = '审核';
      this.setState({
        taskformFields: defaultFields,
        formValues: { approval, comment, own_noticeDescription: noticeDescription, own_receivers: receivers },
        releaseNotice, formVisible: true,
      });
    }
  }

  handleTableChange = (pagination, type = 'tasksPage') => {
    const {
      tasksPage: { pageSize: tpageSize },
      logsPage: { pageSize: lpageSize },
    } = this.state;
    if (type === 'tasksPage') {
      const newCurrent = tpageSize === pagination.pageSize ? pagination.current : 1;
      this.setState({ tasksPage: { pageSize: pagination.pageSize, current: newCurrent } }, () => {
        this.getCurrentTasks();
      });
    } else if (type === 'logsPage') {
      const newCurrent = lpageSize === pagination.pageSize ? pagination.current : 1;
      this.setState({ logsPage: { pageSize: pagination.pageSize, current: newCurrent } }, () => {
        this.getProcessLogs();
      });
    }
  } */

  handleExit = () => {
    const {handleExit} = this.props;
    if (handleExit) handleExit();
  };

  /* handleExpandable = (record) => {
    let expandedRowKeys = [record.taskId];
    if (this.expandeId === record.taskId) {
      expandedRowKeys = [];
      this.expandeId = '';
    } else {
      this.expandeId = record.taskId;
    }
    this.setState({ expandedRowKeys });
  }

  handleTabChange = (activeKey) => {
    if (activeKey === 'logs') {
      if (this.isLogLoaded) return;
      this.isLogLoaded = true;
      this.getProcessLogs();
    }
  } */

  customFormVisible = (visible, record = "") => {
    const {dispatch} = this.props;
    this.record = record;
    if (visible === true) {
      this.handleTaskForm(record, visible);
    } else {
      dispatch({type: "FlowExecution/get/getForm", payload: []});
      // this.setState({ formVisible: visible, noticeBusinessSystem: !!record.noticeBusinessSystem });
      this.setState({formVisible: visible});
    }
  };

  handleTaskForm = (record, visible) => {
    const {taskId} = record || {};
    this.taskId = taskId;
    const {dispatch, showSaveDraft} = this.props;
    dispatch({
      type: "FlowHandle/getTaskform",
      payload: {taskId},
    }).then(({errCode, errMsg, datas}) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon(
          "error",
          "",
          errMsg || "获取处理表单信息失败",
        );
      } else if (
        !datas ||
        !datas.fields ||
        JSON.stringify(datas.fields) === "{}"
      ) {
        Modal.confirm({
          title: "当前暂无表单，可点击确认直接处理",
          okText: "确认",
          cancelText: "取消",
          onOk: () => this.handleFormSave({}),
          onCancel: this.handleCancel,
        });
      } else {
        const {fieldData} = datas;
        // this.setState({ formVisible: visible, formDraftData: showSaveDraft ? fieldData : undefined, noticeBusinessSystem: !!record.noticeBusinessSystem  });
        this.setState({
          formVisible: visible,
          formDraftData: showSaveDraft ? fieldData : undefined,
        });
      }
    });
  };

  handleFormSave = (values, isDraft = false, taskId) => {
    const {afterSave, flowHandleStore} = this.props;
    const {taskformFields = {}, isExternalForm, formId} = flowHandleStore;
    const payload = {
      variables: values,
      taskId,
    };
    let type = "FlowHandle/handleTask";
    let hint = "任务处理";
    if (isDraft) {
      type = "FlowHandle/handleDraft";
      hint = "暂存";
    }
    const {dispatch} = this.props;
    if (isExternalForm === true) {
      dispatch({
        type: "FlowHandle/handleTask",
        payload: {
          taskId,
          formId,
        },
      }).then(({errCode, errMsg}) => {
        if (errCode === 0) {
          this.customFormVisible(false);
          this.openNotificationWithIcon("success", "", `${hint}成功`);
          this.getDetailData();
        } else {
          this.openNotificationWithIcon("error", "", errMsg || `${hint}失败`);
        }
      });
    } else {
      dispatch({
        type,
        payload,
      }).then(({errCode, errMsg}) => {
        if (errCode !== 0) {
          this.openNotificationWithIcon("error", "", errMsg || `${hint}失败`);
        } else {
          this.customFormVisible(false);
          this.openNotificationWithIcon("success", "", `${hint}成功`);
          if (afterSave) {
            afterSave(isDraft, {
              ...payload,
              labels: getFormTitleKeyList(taskformFields),
              schema: taskformFields,
            });
          }
          this.getDetailData();
        }
      });
    }
  };

  // 退回弹窗
  handleRollbackVisible = visible => {
    this.setState({rollbackVisible: visible});
  };

  // 撤回弹窗
  handleReturnBackVisible = visible => {
    this.setState({returnBackVisible: visible});
  };

  // 审批意见 通过驳回
  handleApprovalVisible = (visible, value) => {
    this.setState({approvalVisible: visible, comment: value});
  };

  handleCloseApprovalVisible = visible => {
    this.setState({approvalVisible: visible});
  };

  // 指定下一节点
  handleNextNodeVisible = visible => {
    this.setState({nextNodeVisible: visible});
  };

  handleTakeBack = () => {
    const {dispatch} = this.props;
    const userCode = sessionStorage.getItem("USER_CODE") ?? '';


    dispatch({
      type: "FlowHandle/takeBack",
      payload: {
        taskId: this.taskId,
        userCode,
        comment: ''
      },
    }).then(({errCode, errMsg}) => {
      if (errCode === 0) {
        // this.openNotificationWithIcon("success", "", "拿回成功");
        this.getDetailData();
      } else {
        // this.openNotificationWithIcon("error", "", errMsg || "拿回失败");
      }
    })
  }

  // 阅办
  handleReadHandleVisible = visible => {
    this.setState({ readHandleVisible: visible });
  };

  // 催办接口与逻辑
  handlePushDeal = () => {
    const {dispatch} = this.props;

    dispatch({
      type: "FlowHandle/remind",
      payload: {processInstanceId: this.processInstanceId},
    }).then(({errCode, errMsg}) => {
      if (errCode === 0) {
        this.openNotificationWithIcon("success", "", "催办成功");
        this.getDetailData();
      } else {
        this.openNotificationWithIcon("error", "", errMsg || "操作失败");
      }
    });
  };

  // 驳回 弹窗

  handleReject = () => {
    Modal.confirm({
      title: "提示",
      content: "确认要驳回吗？",
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
      },
    });
  };

  // 签收 加签 转办 延期 弹窗
  handleTaskVisible = (lable, visible, taskId, title, applyUserId) => {
    const onCheckOk = timeout => {
      if (isPhone()) {
        const url = getPhoneUrlForHandle(lable, taskId, applyUserId, timeout);
        if (url) {
          router.push(url);
        }
      } else {
        this.setState({[lable]: visible, visibleTitle: title, timeout});
      }
      this.taskId = taskId;
    };
    if (lable === "delayVisible" && visible) {
      const {dispatch} = this.props;
      dispatch({
        type: "FlowHandle/getTaskTimeout",
        payload: {
          taskId,
        },
      }).then(({errCode, errMsg, datas}) => {
        if (errCode === 0) {
          if (moment(datas.task_timeout).isBefore(moment())) {
            this.openNotificationWithIcon(
              "error",
              "",
              `当前时间已超过节点超时时间，不可发起延期`,
            );
            return;
          }
          onCheckOk(datas);
        } else {
          this.openNotificationWithIcon("error", "", errMsg);
        }
      });
    } else {
      onCheckOk();
    }
  };

  // 展开流程图详情弹窗
  handlePictureVisible = visible => {
    this.setState({pictureVisible: visible});
  };

  // 退回弹窗
  handleBackVisible = (visible, title) => {
    this.setState({backVisible: visible, titleText: title});
  };

  handleCancel = () => {
    this.customFormVisible(false);
  };

  loadMessageTheme = (type, noticeThemeCode) => {
    const {dispatch} = this.props;
    return dispatch({
      type: "notice_msg/getNoticeTheme",
      payload: {
        type,
        noticeThemCode: noticeThemeCode,
      },
    });
  };

  handleOk = taskId => {
    const { form, dispatch } = this.props;
    const { titleText } = this.state;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      dispatch({
        type: titleText === "退回到上一节点"
            ? "FlowHandle/rollbackToPreNode"
            : "FlowHandle/rollbackToFirstNode",
        payload: {
          workItemId: taskId,
          participantId: sessionStorage.getItem("USER_ID"),
          participantName: sessionStorage.getItem("USER_NAME"),
          comment: values.comment,
        },
      }).then(({errCode, errMsg}) => {
        if (errCode === 0) {
          this.handleBackVisible(false);
          this.openNotificationWithIcon("success", "", `审批意见${titleText}成功`);
          this.getDetailData();
        } else {
          this.openNotificationWithIcon("error", "", errMsg);
        }
      });
    });
  };

  render() {
    const {
      flowHandleStore,
      loading,
      // hiddenBtn = false,
      dispatch,
      noticeThemeTypeList,
      // showSaveDraft,
      form,
    } = this.props;
    const {getFieldDecorator} = form;
    const {
      //  expandedRowKeys, logsPage, tasksPage,
      formVisible,
      // formValues,
      rollbackVisible,
      rollbackInfo,
      // releaseNotice,
      pictureVisible,
      returnBackVisible,
      signVisible,
      addSignVisible,
      transferVisible,
      rejectVisible,
      delayVisible,
      timeout,
      // noticeBusinessSystem,
      formDraftData,
      approvalVisible,
      moreBtnVisible,
      nextNodeVisible,
      visibleTitle,
      comment,
      backVisible,
      forcePickIndex,
      readHandleVisible,
      attachInfoList,
      forcePickComplete,
      hasForcePick,
      titleText
    } = this.state;

    const {
      processDetailData = {},
      flowRecords = [],
      taskformFields = {},
      flowformLog = {},
      fieldData = {},
      // logsTotalCount, tasksTotalCount, // processLogs = [], // processTasks = [],
      formUrl = "",
      exDisplayStyle = "",
      exShowAsUrl = "",
      showExternalFormUrl = "",
      displayStyle = "",
      showAsUrl = "",
      formName = "",
      isExternalForm,
      nextTaskDetailData,
      candidateTask = {},
      mustExpress = true,
    } = flowHandleStore;
    const externalUrl = `${showExternalFormUrl}&generateId=${this.uuid}`;
    const u = sessionStorage.getItem("USER_CODE");
    let result = candidateTask;
    // eslint-disable-next-line array-callback-return
    // flowRecords.map(item => {
    //   if (item.children?.length > 0) {
    //     // eslint-disable-next-line array-callback-return
    //     item.children.map(v => {
    //       if (
    //         v.operatorCode === u &&
    //         v.status === "NORMAL" &&
    //         v.taskStatus === "TODO"
    //       )
    //         result = v;
    //     });
    //   } else if (
    //     item.operatorCode === u &&
    //     item.status === "NORMAL" &&
    //     item.taskStatus === "TODO"
    //   ) {
    //     result = item;
    //   } else if (item.nodeAuthShow === true && item.nodeAuth.signIn === true) {
    //     result = item;
    //   }
    // });
    const {nodeAuth = {}} = result;
    let array = [];
    if (flowRecords && flowRecords.length > 1){
      const map = new Map();
      flowRecords.filter(flowRecord => flowRecord.activityId).forEach(flowRecord => {
        if (map.get(flowRecord.activityId)){
          array = array.slice(0, map.get(flowRecord.activityId)-1);
        }else {
          map.set(flowRecord.activityId, array.length+1);
        }
        array.push(flowRecord);
      });
    }

    const {process = {}, model = {}} = processDetailData;
    let newModel = model;

    if (newModel.nodes?.length > 0 && array.length > 0){
      const map = new Map();
      array.filter(flowRecord => flowRecord.taskStatus === "DONE").forEach(flowRecord => {
        map.set(flowRecord.activityId, "y");
      })
      newModel.nodes = newModel.nodes.map(node =>{
        const newVar = map.get(node.model.properties.overrideid);
        if (newVar){
          node.status = newVar;
        }
        return node;
      })
    }
    const {applyUserId} = process;
    const dataLoading = loading.effects["FlowHandle/getProcess"] || false;
    const confirmLoading = loading.effects["FlowHandle/recall"] || false;
    const rejectConfirmLoading = loading.effects["FlowHandle/reject"] || false;
    const transferConfirmLoading =
      loading.effects["FlowHandle/turnTask"] || false;
    const signConfirmLoading =
      loading.effects["FlowHandle/handleTaskclaim"] || false;
    const addSignConfirmLoading =
      loading.effects["FlowHandle/addSignTask"] || false;
    const delayConfirmLoading =
      loading.effects["FlowHandle/delayTask"] || false;
    const loadingMessageTheme =
      loading.effects["notice_msg/getNoticeTheme"] || false;

    const handleTaskLoading = loading.effects["FlowHandle/handleTask"] || false;
    const handleDraftLoading =
      loading.effects["FlowHandle/handleDraft"] || false;
    const formLoading = loading.effects["FlowHandle/getTaskform"] || false;
    const nextNodeLoading =
      loading.effects["FlowHandle/getNextTaskDetail"] ||
      loading.effects["FlowHandle/postNextNodeAssignee"] ||
      false;
    const flowformLogLoading =
      loading.effects["FlowHandle/getStartFormDetail"] || false;
    const submitLoading = loading.effects["FlowHandle/handleWithClaim"] || false;
    const terminateProcessLoading = loading.effects["FlowHandle/terminateProcessInstance"] || false;
    const listLoading = loading.effects["FlowHandle/getFlowRecords"] || false;
    // const tasksLoding = loading.effects['FlowHandle/getCurrentTasks'];
    // const logsLoding = loading.effects['FlowHandle/handleLogs'];
    // const logsPagination = { ...this.basePagination, ...logsPage, total: logsTotalCount };
    // const tasksPagination = { ...this.basePagination, ...tasksPage, total: tasksTotalCount };

    const nextLoading =
      loading.effects["usertreeSelect/selectEmployeeList"] ||
      loading.effects["FlowChart/getUserPositionPageList"] ||
      loading.effects["FlowChart/getUserGroupPageList"] ||
      loading.effects["FlowChart/getUserRolePageList"] ||
      false;

    // const pictureExtra = (
    //   <span
    //     onClick={() => {
    //       this.handlePictureVisible(true);
    //     }}
    //     style={{ cursor: "pointer" }}
    //   >
    //     <Icon type="file-image" style={{ paddingRight: "8px" }} />
    //     查看流程图
    //   </span>
    // );
    let showMore = false;

    if (nodeAuth) {
      showMore =
        nodeAuth?.addSignature ||
        nodeAuth?.minusSignature ||
        nodeAuth?.delegate ||
        nodeAuth?.transfer ||
        nodeAuth?.turnRead ||
        nodeAuth?.readHandle ||
        nodeAuth?.veto;
    }

    // const menu = (
    //   <Menu>
    //     {nodeAuth?.addSignature && (
    //       <Menu.Item>
    //         <span
    //           onClick={() => {
    //             this.handleTaskVisible(
    //               "moreBtnVisible",
    //               true,
    //               result.taskId,
    //               "加签",
    //             );
    //           }}
    //         >
    //           加签
    //         </span>
    //       </Menu.Item>
    //     )}
    //     {nodeAuth?.minusSignature && (
    //       <Menu.Item>
    //         <span
    //           onClick={() => {
    //             this.handleTaskVisible(
    //               "moreBtnVisible",
    //               true,
    //               result.taskId,
    //               "减签",
    //             );
    //           }}
    //         >
    //           减签
    //         </span>
    //       </Menu.Item>
    //     )}
    //     {nodeAuth?.delegate && (
    //       <Menu.Item>
    //         <span
    //           onClick={() => {
    //             this.handleTaskVisible(
    //               "moreBtnVisible",
    //               true,
    //               result.taskId,
    //               "委派",
    //             );
    //           }}
    //         >
    //           委派
    //         </span>
    //       </Menu.Item>
    //     )}
    //     {nodeAuth?.transfer && (
    //       <Menu.Item>
    //         <span
    //           onClick={() => {
    //             this.handleTaskVisible(
    //               "moreBtnVisible",
    //               true,
    //               result.taskId,
    //               "转办",
    //             );
    //           }}
    //         >
    //           转办
    //         </span>
    //       </Menu.Item>
    //     )}

    //     {/* {nodeAuth.turnRead && (
    //       <Menu.Item>
    //         <span
    //           onClick={() => {
    //             this.handleTaskVisible("moreBtnVisible", true, result.taskId, '转阅');
    //           }}
    //         >
    //           转阅
    //         </span>
    //       </Menu.Item>
    //     )} */}
    //     {nodeAuth?.readHandle && (
    //       <Menu.Item>
    //         <span
    //           onClick={() => {
    //             this.handleTaskVisible(
    //               "readHandleVisible",
    //               true,
    //               result.taskId,
    //               "阅办",
    //             );
    //           }}
    //         >
    //           阅办
    //         </span>
    //       </Menu.Item>
    //     )}
    //      {nodeAuth?.veto && (
    //       <Menu.Item>
    //         <span
    //           onClick={() => {
    //             this.handleApprovalVisible(true, 'end', this.taskId);
    //           }}
    //         >
    //           否决
    //         </span>
    //       </Menu.Item>
    //     )}
    //   </Menu>
    // );

    return (
      <>
        {displayStyle !== "" && displayStyle !== "standard" ? (
          <div className={styles.root}>
            <IframeWrapper
              autoFitHeight
              src={externalUrl}
              style={{height: '100vh'}}
              iframeStyle={{height: "100%"}}
              getFrameRef={ref => {
                this.iframeRef = ref;
              }}
            />
          </div>
        ) : null}
        {displayStyle === "" || displayStyle === "standard" ? (
          <div className={styles.root}>
            <Spin spinning={dataLoading || listLoading} delay={300}>
              {/* <Card title="流程图" bordered={false} className={styles.flowchart}>
            <FlowChartDetail data={model} dataLoading={dataLoading} />
          </Card> */}
              <div className={styles.top}>
                <div className={styles.top_opt}>
                  <span className={styles.name}>{process?.busiName}</span>
                  {/* <div>
                    <Button
                      className={styles.btn}
                      type="primary"
                      onClick={() => {
                      this.handleApprovalVisible(true, 'handle', result.taskId);
                    }}
                      disabled={result.taskStatus !== "TODO" && result.status !== "NORMAL"}
                    >
                      通过
                    </Button>
                    {result.exclusiveFlag === 1 ? (
                      <Button
                        onClick={() => {
                          this.handleApprovalVisible(true, 'rollback', result.taskId);
                        }}
                        disabled={result.taskStatus !== "TODO" && result.status !== "NORMAL"}
                      >
                        驳回
                      </Button>
                    ): (
                      <Button
                        onClick={() => {
                          this.handleApprovalVisible(true, 'end', result.taskId);
                        }}
                        disabled={result.taskStatus !== "TODO" && result.status !== "NORMAL"}
                      >
                        拒绝
                      </Button>
                  )}
                  </div> */}
                  <Button
                    className={(nodeAuth?.takeBack && result?.taskStatus === "DONE" || nodeAuth?.rollbackToPre || nodeAuth?.rollbackToFirst) ? styles.btn : ''}
                    type="primary"
                    onClick={() => {

                      this.handleApprovalVisible(true, "handle", this.taskId);

                      // this.setState({forcePickComplete:() => {
                      //   this.handleApprovalVisible(true, "handle", this.taskId);
                      // }}, () => {
                      //   this.handleForcePick();
                      // });

                    }}
                    disabled={
                      result?.taskStatus !== "TODO" && result.status !== "NORMAL"
                    }
                  >
                    提交
                  </Button>
                  {nodeAuth?.takeBack && result?.taskStatus === "DONE" && (
                    <Popconfirm
                      title="确定拿回吗？"
                      okText="确定"
                      cancelText="取消"
                      onConfirm={() => this.handleTakeBack()}
                    >
                      <Button
                        className={(nodeAuth?.rollbackToPre || nodeAuth?.rollbackToFirst) ? styles.btn : ''}
                        type="primary"
                      >
                        拿回
                      </Button>
                    </Popconfirm>
                  )}
                  {/* {nodeAuth?.rollback && (
                    <Button
                      type="primary"
                      onClick={() => {
                        this.handleBackVisible(true);
                      }}
                    >
                      退回
                    </Button>
                  )} */}
                  {nodeAuth?.rollbackToPre && (
                    <Button
                      className={nodeAuth?.rollbackToFirst? styles.btn : ''}
                      type="primary"
                      onClick={() => {
                        this.handleBackVisible(true, '退回到上一节点');
                      }}
                    >
                      退回到上一节点
                    </Button>
                  )}
                  {nodeAuth?.rollbackToFirst && (
                    <Button
                      type="primary"
                      onClick={() => {
                        this.handleBackVisible(true, '退回到第一个节点');

                      }}
                    >
                      退回到第一个节点
                    </Button>
                  )}
                  <div className={styles.vertical}/>
                  <div>
                    <Button
                      className={styles.btn}
                      onClick={() => {
                        this.handlePictureVisible(true);
                      }}
                    >
                      查看流程图
                    </Button>
                    {/* {nodeAuth.nextNode && (
                  <Button
                    className={styles.btn}
                    onClick={() => {
                      this.handleNextNodeVisible(true);
                    }}
                  >
                    指定下一节点
                  </Button>
                )} */}
                    {/* {nodeAuth.nextNodeHandler && (
                      <Button
                        className={styles.btn}
                        onClick={() => {
                    this.handleTaskVisible("moreBtnVisible", true, result.taskId, '指定下一节点处理人');
                  }}
                      >
                        指定下一节点处理人
                      </Button>
                )} */}

                    {nodeAuth?.nextNodeHandler && (
                      <Button
                        className={styles.btn}
                        onClick={() => {
                          this.setState({forcePickComplete:null}, () => {
                            this.handleTaskVisible(
                              "nextNodeVisible",
                              true,
                              result.taskId,
                              "指定后续节点处理人",
                            );
                          });
                        }}
                      >
                        指定后续节点处理人
                      </Button>
                    )}
                    {/* {showMore && (
                      <Dropdown overlay={menu} placement="bottomRight">
                        <Button>更多</Button>
                      </Dropdown>
                    )} */}
                    {nodeAuth?.addSignature && (
                      <Button
                        type="primary"
                        className={styles.btn}
                        onClick={() => {
                          this.handleTaskVisible(
                            "moreBtnVisible",
                            true,
                            result.taskId,
                            "加签",
                          );
                        }}
                      >
                        加签
                      </Button>
                    )}
                    {nodeAuth?.minusSignature && (
                      <Button
                        type="primary"
                        className={styles.btn}
                        onClick={() => {
                          this.handleTaskVisible(
                            "moreBtnVisible",
                            true,
                            result.taskId,
                            "减签",
                          );
                        }}
                      >
                        减签
                      </Button>
                    )}
                    {nodeAuth?.delegate && (
                      <Button
                        type="primary"
                        className={styles.btn}
                        onClick={() => {
                          this.handleTaskVisible(
                            "moreBtnVisible",
                            true,
                            result.taskId,
                            "委派",
                          );
                        }}
                      >
                        委派
                      </Button>
                    )}
                    {nodeAuth?.transfer && (
                      <Button
                        type="primary"
                        className={styles.btn}
                        onClick={() => {
                          this.handleTaskVisible(
                            "moreBtnVisible",
                            true,
                            result.taskId,
                            "转办",
                          );
                        }}
                      >
                        转办
                      </Button>
                    )}
                    {nodeAuth?.readHandle && (
                      <Button
                        type="primary"
                        className={styles.btn}
                        onClick={() => {
                          this.handleTaskVisible(
                            "readHandleVisible",
                            true,
                            result.taskId,
                            "阅办",
                          );
                        }}
                      >
                        阅办
                      </Button>
                    )}
                    {nodeAuth?.veto && (
                      <Button
                        type="primary"
                        className={styles.btn}
                        onClick={() => {
                          this.handleApprovalVisible(true, 'end', this.taskId);
                        }}
                      >
                        否决
                      </Button>
                    )}
                  </div>
                </div>
              </div>

              <Card title="流程说明" bordered={false}>
                <ProcessInfo data={process}/>
              </Card>
              {attachInfoList?.length > 0 && <Card title="附件列表" bordered={false}>
                {(attachInfoList || []).map(file => {
                  return (
                    <FileView
                      key={file.id}
                      fileMessage={file}
                      serviceType='0'
                    />
                  );
                })}
              </Card>}
              <Card
                title="审批进度"
                bordered={false}
                bodyStyle={{padding: "24px 0 24px 24px"}}
              >
                <ProcessRecord
                  dispatch={dispatch}
                  data={process}
                  flowRecords={flowRecords}
                  handleTaskVisible={(label, visible, taskId) =>
                    this.handleTaskVisible(label, visible, taskId, applyUserId)
                  }
                  customFormVisible={this.customFormVisible}
                  actype={this.actype}
                  processInstanceId={this.processInstanceId}
                  result={result}
                />
              </Card>
              {isExternalForm === true && (
                <Card title="流程表单" bordered={false}>
                  {/* {displayStyle === "standard" && showAsUrl === 'Y' &&
                      <a href={externalUrl} target="_blank" rel="noreferrer">{formName}</a>
                    } */}

                  {/* {displayStyle === "standard" && showAsUrl === 'N' && ( */}
                  <IframeWrapper
                    autoFitHeight
                    src={externalUrl}
                    style={{height: 1000}}
                    iframeStyle={{height: 1000}}
                    getFrameRef={ref => {
                      this.iframeRef = ref;
                    }}
                  />
                  {/* <IframeAutoFit iframeId="iframeId" src={externalUrl} /> */}
                  {/* )} */}
                </Card>
              )}
              {JSON.stringify(flowformLog) !== "[]" && JSON.stringify(flowformLog) !== "{}" && isExternalForm === false && (
                <Card title="流程发起表单" bordered={false}>
                  <RecordForm
                    formConfigData={flowformLog}
                    dataLoading={flowformLogLoading}
                    fieldData={fieldData}
                  />
                </Card>
              )}
              {/*
          <div className={styles.tab_box}>
            <Tabs defaultActiveKey="task" onChange={this.handleTabChange}>
              <TabPane tab="当前任务" key="task">
                <Table
                  columns={this.columnsr}
                  expandedRowKeys={expandedRowKeys}
                  expandedRowRender={record => <ExpandedRowContent record={record} />}
                  dataSource={processTasks}
                  loading={!dataLoading && tasksLoding}
                  rowKey='taskId'
                  expandIcon={null}
                  rowClassName='row_hover_none'
                  pagination={tasksPagination}
                  onChange={(pagination) => { this.handleTableChange(pagination, 'tasksPage') }}
                />
              </TabPane>
              <TabPane tab="处理日志" key="logs">
                <Table
                  dataSource={processLogs}
                  rowKey={record => (`${record.taskId}${record.taskName}${record.assignee}${record.endTime}`)}
                  columns={this.columns}
                  loading={!dataLoading && logsLoding}
                  pagination={logsPagination}
                  onChange={(pagination) => { this.handleTableChange(pagination, 'logsPage') }}
                />
              </TabPane>
            </Tabs>
          </div>
          */}
              {/* {!hiddenBtn && (
            <div className={[styles.btns, 'dynamic-theme'].join(' ')} style={(isPhone() ? { margin: 0 } : {})}>
              <Button onClick={this.handleExit}>返回</Button>
              {this.actype === "apply" && process.canRecall && (
              <div>
                <Button
                  type="primary"
                  onClick={() => {
                      this.handleReturnBackVisible(true);
                    }}
                >
                  撤回
                </Button>
              </div>
              )}
              {this.actype === "apply" && process.canRemind && (
                <Button
                  type="primary"
                  onClick={this.handlePushDeal}
                >
                  催办
                </Button>
              )}
            </div>
          )} */}
            </Spin>
            {formVisible && (
              <CustomForm
                title="处理"
                visible={formVisible}
                confirmLoading={handleTaskLoading || handleDraftLoading}
                onOk={values => {
                  this.handleFormSave(values, false, result.taskId);
                }}
                onSaveDraft={values => {
                  this.handleFormSave(values, true);
                }}
                onCancel={this.handleCancel}
                formConfigData={taskformFields}
                dataLoading={formLoading}
                emptyWord="当前无表单，可直接处理"
                action="处理"
                // noticeBusinessSystem={noticeBusinessSystem}
                noticeBusinessSystem
                showSaveDraft={false}
                initialValues={formDraftData}
                formUrl={formUrl}
                displayStyle={exDisplayStyle}
                showAsUrl={exShowAsUrl}
                isExternalForm={isExternalForm}
              />
            )}
            {rollbackVisible && (
              <RollbackForm
                visible={rollbackVisible}
                confirmLoading={false}
                onCancel={this.handleRollbackVisible}
                disable={isTrue}
                isView={isTrue}
                data={rollbackInfo}
              />
            )}
            {returnBackVisible && (
              <ReturnBackForm
                visible={returnBackVisible}
                confirmLoading={confirmLoading}
                onCancel={this.handleReturnBackVisible}
                dispatch={dispatch}
                processInstanceId={this.processInstanceId}
                getList={this.getDetailData}
              />
            )}
            {rejectVisible && (
              <RejectForm
                visible={rejectVisible}
                confirmLoading={rejectConfirmLoading}
                onCancel={this.handleTaskVisible}
                dispatch={dispatch}
                taskId={this.taskId}
                getList={this.getDetailData}
              />
            )}
            {signVisible && (
              <SignForm
                visible={signVisible}
                confirmLoading={signConfirmLoading}
                onCancel={this.handleTaskVisible}
                dispatch={dispatch}
                taskId={this.taskId}
                getList={this.getDetailData}
                applyUserId={applyUserId}
                loadMessageTheme={this.loadMessageTheme}
                loadingMessageTheme={loadingMessageTheme}
                noticeThemeTypeList={noticeThemeTypeList}
              />
            )}
            {addSignVisible && (
              <AddSignForm
                visible={addSignVisible}
                confirmLoading={addSignConfirmLoading}
                onCancel={this.handleTaskVisible}
                dispatch={dispatch}
                taskId={this.taskId}
                getList={this.getDetailData}
                applyUserId={applyUserId}
                loadMessageTheme={this.loadMessageTheme}
                loadingMessageTheme={loadingMessageTheme}
                noticeThemeTypeList={noticeThemeTypeList}
              />
            )}
            {transferVisible && (
              <TransferForm
                visible={transferVisible}
                confirmLoading={transferConfirmLoading}
                onCancel={this.handleTaskVisible}
                dispatch={dispatch}
                taskId={this.taskId}
                getList={this.getDetailData}
                applyUserId={applyUserId}
                loadMessageTheme={this.loadMessageTheme}
                loadingMessageTheme={loadingMessageTheme}
                noticeThemeTypeList={noticeThemeTypeList}
              />
            )}
            {delayVisible && (
              <DelayForm
                visible={delayVisible}
                confirmLoading={delayConfirmLoading}
                onCancel={this.handleTaskVisible}
                dispatch={dispatch}
                taskId={this.taskId}
                getList={this.getDetailData}
                timeout={timeout}
                applyUserId={applyUserId}
                loadMessageTheme={this.loadMessageTheme}
                loadingMessageTheme={loadingMessageTheme}
                noticeThemeTypeList={noticeThemeTypeList}
              />
            )}
            {pictureVisible && (
              <Modal
                width={800}
                visible={pictureVisible}
                title="查看流程图"
                onCancel={() => {
                  this.handlePictureVisible(false);
                }}
                footer={[
                  <Button
                    key="back"
                    onClick={() => {
                      this.handlePictureVisible(false);
                    }}
                  >
                    关闭
                  </Button>,
                ]}
              >
                <FlowChartDetail data={newModel? newModel : model} dataLoading={dataLoading} flowRecords={array.length > 0 ? array : flowRecords} />
              </Modal>
            )}
            {approvalVisible && (
              <ApprovalForm
                comment={comment}
                visible={approvalVisible}
                confirmLoading={submitLoading || terminateProcessLoading}
                onCancel={this.handleCloseApprovalVisible}
                dispatch={dispatch}
                processInstanceId={this.processInstanceId}
                uuid={this.uuid}
                taskId={result.taskId}
                activityId={result.activityId}
                getList={this.getDetailData}
                isHandle
                mustExpress={mustExpress}
              />
            )}
            {moreBtnVisible && (
              <MoreBtnForm
                title={visibleTitle}
                visible={moreBtnVisible}
                confirmLoading={addSignConfirmLoading}
                onCancel={this.handleTaskVisible}
                dispatch={dispatch}
                taskId={result.taskId}
                applyUserId={applyUserId}
                loadMessageTheme={this.loadMessageTheme}
                loadingMessageTheme={loadingMessageTheme}
                noticeThemeTypeList={noticeThemeTypeList}
                getList={this.getDetailData}
              />
            )}
            {nextNodeVisible && (
              <NextNodeForm
                forcePickComplete={forcePickComplete}
                forcePickIndex={forcePickIndex}
                visible={nextNodeVisible}
                nextNodeLoading={nextNodeLoading || nextLoading}
                onCancel={this.handleNextNodeVisible}
                dispatch={dispatch}
                processInstanceId={this.processInstanceId}
                activityId={result.activityId}
                nextTaskDetailData={nextTaskDetailData}
                taskId={result.taskId}
                getList={this.getDetailData}
              />
            )}
             {readHandleVisible && (
              <ReadHandleForm
                visible={readHandleVisible}
                nextNodeLoading={nextNodeLoading}
                onCancel={this.handleReadHandleVisible}
                dispatch={dispatch}
                processInstanceId={this.processInstanceId}
                activityId={result.activityId}
                nextTaskDetailData={nextTaskDetailData}
                taskId={result.taskId}
                getList={this.getDetailData}
                disable={false}
              />
            )}
            {backVisible && (
              <Modal
                width={800}
                onOk={() => {
                  this.handleOk(result.taskId);
                }}
                visible={backVisible}
                title={`${titleText}`}
                destroyOnClose
                onCancel={() => {
                  this.handleBackVisible(false);
                }}
                footer={[
                  <Button
                    type="primary"
                    onClick={() => {
                      this.handleOk(result.taskId);
                    }}
                  >
                    确定
                  </Button>,
                  <Button
                    onClick={() => {
                      this.handleBackVisible(false);
                    }}
                  >
                    取消
                  </Button>,
                ]}
              >
                <Form>
                  {/* <Form.Item label="">
                    {getFieldDecorator("rollbackToNode", {
                      rules: [{required: true, message: "请选择"}],
                    })(
                      <Radio.Group>
                        <Radio value="rollbackToPreNode">退回到上一节点</Radio>
                        <Radio value="rollbackToFirstNode">
                          退回给第一个审批节点
                        </Radio>
                      </Radio.Group>,
                    )}
                  </Form.Item> */}
                  <Form.Item label="">
                    {getFieldDecorator("comment", {
                      rules: [
                        {max: 1000, message: "请不要超过1000个字符"},
                        // {required: true, message: "请输入审批意见"},
                      ],
                    })(
                      <TextArea
                        placeholder="请输入审批意见，最大限制在1000个字数内"
                        rows={5}
                      />,
                    )}
                  </Form.Item>
                </Form>
              </Modal>
            )}
          </div>
        ) : null}
      </>
    );
  }
}

export default FlowDataDetail;
